package com.kyubi.xmlsynth.source;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import com.kyubi.common.data.Instances;

/**
 * A class representing the base data source class.
 * 
 * @author anand
 *
 */
public class DataSource implements IDataSource {
	
	protected Instances insts = null;
	
	public DataSource() {
		insts = new Instances();
	}
	
	/**
	 * Set the data source file path.
	 * 
	 * @param	filePath	the path of the data source file
	 */
	public void setSource(String filePath) {
		readFile(filePath);
	}
	
	/**
	 * Function to tokenize a line
	 * 
	 * @param line	the String line
	 * @return	an array of tokens generated
	 * @throws NotImplementedException
	 */
	protected String[] tokenize(String line) throws NotImplementedException {
		throw new NotImplementedException();
	}
	
	/**
	 * Function to read the file
	 * 
	 * @param path	the path of the file
	 */
	protected void readFile(String path) {
		BufferedReader rdr = null;
        String line;

        try {
            rdr = new BufferedReader(new FileReader(path));
        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
        }

        try {
            while ((line = rdr.readLine()) != null) {
            	if(!line.equals("") || !line.startsWith("*")) {
            		line = line.replaceAll("\\[[-\\+0-9a-zA-Z]+\\]", "");
            		
            		String[] tokens = line.split("##");

            		if(tokens.length > 1) {
            			insts.addData(tokens[1]);
            		} else {
            			insts.addData(line.replaceAll("^##", ""));
            		}
            		
            		if(tokens.length > 1 && !line.startsWith("##")) {
            			insts.addLabel(true);
            		} else {
            			insts.addLabel(false);
            		}
            	}
            }
        } catch (IOException io) {
            io.printStackTrace();
        }
	}

	/**
	 * Returns the Instances read from the text file.
	 * 
	 * @return	the Instances read from the data source
	 */
	public Instances get() {		
		return insts;
	}

}
